# -*- coding: utf-8 -*-
import uuid
from typing import List

from loguru import logger
from fastapi import Request
from pydantic import BaseModel

from db.repository.knowledge import db_get_all_kbs, db_get_kbs_by_user, db_get_kb_by_id
from db.repository.user import db_get_user_group_ids
# dialog > conversation
from db.repository.conversation import db_get_dialog_by_role, db_delete_dialog_by_id, \
    db_get_superman_conversation, db_get_admin_conversation, db_get_other_conversation, db_delete_conversation, \
    db_save_dialog, db_update_dialog_by_id
from schemas.response_entity import JsonModel


class DelDialogEntity(BaseModel):
    token: str
    dialog_id: uuid.UUID


class DelConversionEntity(BaseModel):
    token: str
    conversion_id: uuid.UUID = None


class AddDialogEntity(BaseModel):
    name: str
    token: str
    dialog_type: int
    kb_ids: List[uuid.UUID] = []
    dialog_id: uuid.UUID = None


class UDialogEntity(BaseModel):
    name: str = None
    token: str
    kb_ids: List[uuid.UUID] = []
    dialog_id: uuid.UUID = None


# dialog 列表
async def get_list_dialog(request: Request, dialog_type: int = 1, page: int = 1, page_size: int = 10):
    try:
        user = request.state.user
        if user is None:
            return JsonModel(code=401, data=None, msg="用户token非法").to_response()

        offset = (page - 1) * page_size

        total, dialogs = db_get_dialog_by_role(user, offset, page_size, dialog_type)
        return JsonModel(
            code=200,
            data={
                "items": [i.to_json() for i in dialogs],
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            },
            msg=f"success"
        ).to_response()
    except Exception as e:
        logger.error(f"Error: {e}")
        JsonModel(code=500, data=None, msg=f"服务出错").to_response()


# conversation 列表
async def get_list_conversation(request: Request, dialog_id: uuid.UUID):
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token非法").to_response()

    if user.check_superman_role():
        conversations = db_get_superman_conversation(dialog_id)
    elif user.check_admin_role():
        conversations = db_get_admin_conversation(user.id, dialog_id)
    else:
        conversations = db_get_other_conversation(user.id, dialog_id)

    conversation_list = [i.to_json() for i in conversations]
    return JsonModel(code=200, data=conversation_list, msg=f"success").to_response()


# 删除dialog
async def delete_dialog(request: Request, payload: DelDialogEntity):
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token非法").to_response()

    dialog_delete_state = db_delete_dialog_by_id(user.id, payload.dialog_id)
    if dialog_delete_state is True:
        return JsonModel(code=200, data=None, msg=f"删除对话成功").to_response()
    elif dialog_delete_state is None:
        return JsonModel(code=400, data=None, msg=f"对话不存在").to_response()


# 删除 conversation
async def delete_conversion(request: Request, payload: DelConversionEntity):
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token非法").to_response()

    conversion = db_delete_conversation(user.id, payload.conversion_id)
    if conversion is True:
        return JsonModel(code=200, data=None, msg=f"删除会话记录成功").to_response()
    elif conversion is None:
        return JsonModel(code=400, data=None, msg=f"会话不存在").to_response()


# 创建新dialog
async def add_dialog(request: Request, payload: AddDialogEntity):
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token非法").to_response()

    if not payload.kb_ids:
        # 如果不传，默认赋值有访问权限的kd_id
        if user.check_superman_role():
            kbs = db_get_all_kbs()
            payload.kb_ids = [str(kb.id) for kb in kbs]
        else:
            user_group = db_get_user_group_ids(user)
            kbs = db_get_kbs_by_user(user, user_group)
            payload.kb_ids = [str(i.id) for i in kbs]
    else:
        for kb_id in payload.kb_ids:
            kb = db_get_kb_by_id(kb_id)
            if kb is None or not kb.check_permit(user, None):
                return JsonModel(
                    code=400,
                    data=None,
                    msg=f"知识库:{kb_id}不存在,请更换知识库"
                ).to_response()

    # 创建对话
    dialog = db_save_dialog(payload.name, user.id, payload.dialog_type, kb_ids=[str(i) for i in payload.kb_ids])
    return JsonModel(code=200, data={"dialog": f"{dialog.id}"}, msg=f"创建对话{payload.name}成功").to_response()


# 更新 dialog
async def update_dialog(request: Request, payload: UDialogEntity):
    user = request.state.user
    if user is None:
        return JsonModel(code=401, data=None, msg="用户token非法").to_response()

    kb_ids = []
    for kb_id in payload.kb_ids:
        kb = db_get_kb_by_id(kb_id)
        kb_ids.append(str(kb.id))
        if kb is None or not kb.check_permit(user, None):
            return JsonModel(code=400, data=None, msg=f"知识库:{kb_id}不存在,请更换知识库").to_response()

    dialog = db_update_dialog_by_id(user.id, payload.dialog_id, payload.name, payload.kb_ids)
    if dialog is None:
        return JsonModel(code=400, data=None, msg=f"对话未找到").to_response()

    return JsonModel(code=200, data=None, msg=f"更新对话{payload.name}成功").to_response()
